package com.baofu.paycore.manager.storer.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.baofu.paycore.dal.model.base.BaseDO;
import com.baofu.paycore.manager.converter.BO2DOConverter;
import com.baofu.paycore.manager.model.RefundBO;
import com.baofu.paycore.manager.model.SubRefundBO;
import com.baofu.paycore.manager.storage.impl.RefundManager;
import com.baofu.paycore.manager.storer.AbstractOrderRepository;
import com.baofu.paycore.manager.storer.RefundOrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 退款处理Manager
 * <p>
 * </p>
 * User: kwl Date: 2016/6/4 ProjectName: paycore Version: 5.0.0
 */
@Slf4j
@Service
public class RefundOrderRepositoryImpl extends AbstractOrderRepository<RefundBO> implements RefundOrderRepository {

    /**
     * 退款主单处理manager
     */
    @Autowired
    private RefundManager refundManager;

    @Override
    protected List<? extends BaseDO> convertToDO(RefundBO refundBO) {

        List<BaseDO> list = new ArrayList<>();

        //退款主单
        if(null == refundBO){
            return null;
        }
        list.add(BO2DOConverter.getRefundDO(refundBO));

        //退款资金明细单
        List<SubRefundBO> subRefundBOs = refundBO.getSubRefundBOs();
        if(CollectionUtils.isEmpty(subRefundBOs)){
            return list;
        }

        list.addAll(subRefundBOs.stream().map(BO2DOConverter::getSubRefundDO).collect(Collectors.toList()));

        return list;
    }

    @Override
    public RefundBO lock(String requestOrderNo, String requestBizNo,String requestSystem) {
        return null;
    }

    @Override
    public RefundBO load(String fundDetailNo) {
        return refundManager.queryByBankFundDetailNo(fundDetailNo);
    }

    /**
     * 幂等性校验
     *
     * @param requestBizNo      请求流水号
     * @param requestOrderNo    请求订单号
     * @return                  退款订单信息
     */
    @Override
    public RefundBO checkIdempotent(String requestBizNo, String requestOrderNo,String requestSystem) {

        log.debug("退款幂等性校验, requestBizNo:{},requestOrderNo:{}", requestBizNo, requestOrderNo,requestSystem);
        return refundManager.queryByReqInfo(requestBizNo, requestOrderNo);
    }

}
